<#include "../common/header.htm">
<script src="${ctx}/plugins/d3/js_re/D3ForceService.js?_v=6.0.4"></script>
<script src="${ctx}/plugins/d3/js_re/saveSvgAsPng.js"></script>
<script src="${ctx}/dist/echarts2.js"></script>
<div class="content-wrapper" style="height:100%;padding:0 10px;">
    <section class="content" style="height:100%;">
        <div id="inAccount" style="background:#fff;height:100%;display:flex;flex-direction: column;"  >
            <div class="stream_search" >
                <el-form id="listForm" :inline="true"  :model="form" class="demo-form-inline">
                	<el-form-item label="对手信息" v-show="form.sign==1">
                		<el-select v-model="form.detailKeyword" filterable placeholder="请选择">
						    <el-option
						      v-for="item in options"
						      :key="item.VALUE"
						      :label="item.LABEL"
						      :value="item.VALUE">
						    </el-option>
						  </el-select>
                	</el-form-item>
                    <el-form-item class="form_z" label="日期范围">
                        <el-date-picker
                                v-model="form.beginTime"
                                name="beginTime"
                                type="date"
                        >
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item class="el-form-item refsh" label="至">
                        <el-date-picker
                                v-model="form.endTime"
                                name="endTime"
                                type="date"
                        >
                        </el-date-picker>
                    </el-form-item>
                     <el-form-item label="间隔天数">
                        <el-input v-model="form.days" name="days" id="days" placeholder=""></el-input>
                    </el-form-item>
                    <el-form-item label="金额">
                        <el-input v-model="form.minMoney" name="minmoney" id="minmoney" placeholder=""></el-input>
                    </el-form-item>
                    <el-form-item class="refshj" label="至">
                        <el-input v-model="form.maxMoney" name="maxmoney" id="maxmoney" placeholder=""></el-input>
                    </el-form-item>
                    <el-form-item label="经过层级">
                        <el-input v-model="form.levels" name="levels" id="levels" placeholder=""></el-input>
                    </el-form-item>
                    <div class="zcdcon">
                    	<label class="control-label hidden-xs">流向</label>
						<select v-model="form.sign" class="zjzysign">
							<option value="1">支出</option>
							<option value="0">收入</option>
						</select>
                        <el-form-item>
                            <el-button type="primary" @click="onSubmit">分析</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button  @click="clear()">重置</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" class="daobtn" @click="exportExcel" style="width:90px;" >导出数据</el-button>
                        </el-form-item>
                    </div>
                </el-form>
	             <div class="casemanage-switchtip">
	                <div :class="{active:showType==0&&ldx==1}" @click="getView(0,1)" title="交易关系图-开启力导向">
	                    <i class="ldx"></i>
	                </div>
	                <div :class="{active:showType==0&&ldx==0}" v-show="showType==0" @click="getView(0,0)" title="交易关系图-关闭力导向">
	                    <i class="gxt"></i>
	                </div>
	                <div :class="{active:showType==1}" @click="getView(1)" title="时序图">
	                    <i class="sjz"></i>
	                </div>
	                <div :class="{active:showType==2}" @click="getView(2)" title="组织架构">
	                    <i class="zzjg"></i>
	                </div>
	                <div title="切换为列表显示" :class="{active:showType==3}" @click="getView(3)">
	                    <i class="casemanage-switchtip-list"></i>
	                </div>
	                <div title="导出图片" v-show="showType!=3" @click="dc()">
	                    <i class="dc"></i>
	                </div>
	            </div>
            </div>
            <div v-show="showType==0" style="flex:1;overflow: hidden;">
            	<div id="hidebox" style="height:100%;width:100%">
	            </div>
            </div>
            <div class="svzjFontCon" v-show="showType==1">
                <span class="zcline"></span><span class="zcfont">转出</span><span class="hlline"></span><span class="hlfont">回流</span>
            </div>
            <div class="stream_body svzjCon" style="flex:1;overflow: auto;" v-show="showType==1">
                <div class="svzjLeft"></div>
                <canvas id="canvas1" style="padding-right: 20px;"></canvas>
            </div>
            <div v-show="showType==2" style="flex:1;overflow: hidden;" >
            	<div id="chart-panel"></div>
            </div>
            <div v-show="showType==3" style="flex:1;overflow: hidden;" id="dg-box">
            	<table id="dg"></table>
            </div>
        </div>
    </section>
</div>
<div class="loadingMask" style="display:none;">
	<div class="loading">
		<span></span>
		<span></span>
		<span></span>
		<span></span>
	</div>
</div>
<script>
	var d3view = new d3ForceService();
   	d3view.arrowShow=true;
	$(document).ready(function(){
		//_checkedCallback();
	    $(".set-d3box").click(function(){
	        $(".d3-toolbox").fadeToggle(500);
	    })
	    $(window).resize(function(){
	    	if(monthAnalysis.showType==3){
	            $('#dg').datagrid('resize',{
	                height:$("#dg-box").height()
	            });
	    	}
		});
	})

    $('.el-tabs__content').height=($(window).height())-50;

    //计算头部坐标
    var _calcH=function(sp,ep,context){
        var size=6;
        if(sp.y>ep.y){
            return {
                h1:{x:ep.x-size,y:ep.y+size},
                h2:{x:ep.x+size,y:ep.y+size}
            };
        }else{
            return {
                h1:{x:ep.x-size,y:ep.y-size},
                h2:{x:ep.x+size,y:ep.y-size}
            };
        }
    };
    function canvasTextAutoLine(str,canvas,initX,initY,lineHeight){
        var context = canvas.getContext("2d");
        var lineWidth = 0;
        var canvasWidth = 80;
        var lastSubStrIndex= 0;
        context.fillStyle = "#333";
        for(let i=0;i<str.length;i++){
            lineWidth+=context.measureText(str[i]).width;
            if(lineWidth>canvasWidth-initX){//减去initX,防止边界出现的问题
                context.fillText(str.substring(lastSubStrIndex,i),initX,initY);
                initY+=lineHeight;
                lineWidth=0;
                lastSubStrIndex=i;
            }
            if(i==str.length-1){
                context.fillText(str.substring(lastSubStrIndex,i+1),initX,initY);
            }
        }
    }
    let monthAnalysis=new Vue({
        el:"#inAccount",
        data:{
            showType:0,
            tableData: [],
            currentPage:1,
            activeName: 'first',
            options:[],
            form: {
                rivalName: '',
                beginTime: '${yearsago}',
                endTime: '${today}',
                minMoney:"",
                maxMoney:"",
                days:3,
                levels:3,
                sign:1,
                detailKeyword:""
            },
            ldx:1,
            pageSize:10,
            total:"",
            timeline_data:[],
            dist:[],
            end:false,
            isActive:[],
            miaoBaoXieList:[],
            timelineActive:[],
            yearMonth:""
        },
        filters: {

        },
        methods: {
            onSubmit() {
                _checkedCallback2(1);
            },
            exportExcel(){
                var minMoney = "";var maxMoney = "";
                if (this.form.minMoney) minMoney = this.form.minMoney;
                if (this.form.maxMoney) maxMoney = this.form.maxMoney;

                var xhr = new XMLHttpRequest();
                var url="${ctx}bill/stream/moneyFlowPersonalExcel";
                xhr.open('POST', url, true);
                xhr.responseType = "blob";  // 返回类型blob
                // 定义请求完成的处理函数
                xhr.onload = function () {
                    // 请求完成
                    if (this.status === 200) {
                        var content = this.response;
                        var aTag = document.createElement('a');
                        var blob = new Blob([content]);
                        var headerName = xhr.getResponseHeader("Content-disposition");
                        var fileName = decodeURIComponent(headerName).substring(21);
                        aTag.download = fileName;
                        aTag.href = URL.createObjectURL(blob);
                        aTag.click();
                        URL.revokeObjectURL(blob);
                    }
                };
                // 发送ajax请求
                var formdata=new FormData();
                formdata.append("minMoney",minMoney);
                formdata.append("maxMoney",maxMoney);
                formdata.append("checkedAccount",parent.parent._checkedAccount.join(','));
                formdata.append("casemanageId",parent.caseId);
                formdata.append("endTime",getMyDate(this.form.endTime));
                formdata.append("starTime",getMyDate(this.form.beginTime));
                formdata.append("days",this.form.days);
                formdata.append("levels",this.form.levels);
                formdata.append("sign",this.form.sign);
                formdata.append("detailKeyword",this.form.detailKeyword);
                xhr.send(formdata);
            },
            getView(i,ldx){
            	if(i==0){
            		this.ldx=ldx;
            		if(this.showType==0){
	            		d3view.DoChangeForce(!ldx);
            		}else{
    	            	this.showType=i;
		            	_checkedCallback2(1);
            		}
            	}else{
	            	this.showType=i;
	            	_checkedCallback2(1);
            	}
            },
            clear(){
                this.form={
                    rivalName: '',
                    beginTime: '${yearsago}',
                    endTime: '${today}',
                    minMoney:"",
                    maxMoney:"",
                    detailKeyword:"",
                    days:3,
                    levels:3,
                    sign:1
                }
            },
            dc(){
            	if(this.showType==0){
            		d3view.scale_var=1
            		d3view.translate_var=new Array(0,0);
            		d3view.zoom.translate(d3view.translate_var);
            		d3view.zoom.scale(d3view.scale_var);
            		d3view.svg.attr("transform", "translate(" + d3view.translate_var + ")scale(" + d3view.scale_var + ")");
            		
            		if(d3view.theMinx<0) d3view.translate_var[0]=100-d3view.theMinx;
            		if(d3view.theMiny<0) d3view.translate_var[1]=100-d3view.theMiny;
            		
            		d3view.svg.attr("transform", "translate(" + d3view.translate_var + ")scale(" + d3view.scale_var + ")");
            		saveSvgAsPng($("svg")[0], "交易关系图.png",{height:(d3view.theMaxx-d3view.theMinx+400),width:(d3view.theMaxy-d3view.theMiny+400)});
            	}else if(this.showType==1){
	            	downloadCanvasIamge('canvas', '个人资金流向分析')
            	}else if(this.showType==2){
            		jietu();
            	}
            }
        }
    })

    //删除数组指定索引后面的指
    function delArr(arr,index){
        return arr.splice(index+1,arr.length-index-1)
    }
    var arr=""
    function moneyFlow(checkedAccount) {
        $.ajax({
            url:'${ctx}bill/stream/moneyFlowPersonal',
            data:{
            	"checkedAccount":checkedAccount.join(','),
    			"casemanageId":parent.caseId,
    			"starTime":getMyDate(monthAnalysis.form.beginTime),
    			"endTime":getMyDate(monthAnalysis.form.endTime),
    			"minMoney":monthAnalysis.form.minMoney,
    			"maxMoney":monthAnalysis.form.maxMoney,
    			"days":monthAnalysis.form.days,
    			"levels":monthAnalysis.form.levels,
    			"sign":monthAnalysis.form.sign,
    			"detailKeyword":monthAnalysis.form.detailKeyword
				},
            dataType:'json',
            type:'post',
            async:false,
            traditional: true,
            success:function (obj) {
                //第一步，模拟假数据
                var userArr=obj.userArr;
                var flowArr1=obj.flowArr;
                var flowArr= new Array();
                if(userArr){
                    for(var i=0;i<flowArr1.length;i++) {
                        if(flowArr1[i].from!=flowArr1[i].to
                            && userArr.indexOf(flowArr1[i].from)>=0
                            && userArr.indexOf(flowArr1[i].to)>=0){
                            flowArr.push(flowArr1[i]);
                        }
                    }
                }
                var userObject={};
                //第二步，按照假数据，确定canvas大小
                //2.1 宽度根据内容决定，如果内容宽度超出页面宽度，就设置为页面宽度，如果内容宽度小于页面宽度，就设置为页面宽度
                canvasWidth=80*flowArr.length+115;
                svzjRightWidth=($(window).width())-20;
                if(canvasWidth<svzjRightWidth){
                    canvasWidth=$('.stream_body').width()-20;
                }

                //2.2 高度根据内容决定，如果内容高度超出页面高度，就设置为页面高度，如果内容高度小于页面高度，就设置为页面高度
                canvasHeight=70*userArr.length+68;
                var canvas1=document.getElementById("canvas1")
                var context = canvas1.getContext("2d");
                canvas1.width=canvasWidth;
                canvas1.height=canvasHeight;
                $('.stream_body').height(canvasHeight);


                //第三步，绘制人物、姓名、生命线
                for(var i=0;i<userArr.length;i++){
                    context.beginPath();
                    userObject[userArr[i]]={};
                    //创建新的图片对象
                    userObject[userArr[i]].img = new Image();
                    //指定图片的URL
                    userObject[userArr[i]].img.src = "${ctx}imgs/svzjimg.png";
                    //浏览器加载图片完毕后再绘制图片
                    userObject[userArr[i]].img.index=i;
                    userObject[userArr[i]].img.onload = function(){
                        context.drawImage(this, 44, 62+70*this.index, 12, 15);
                    };
                    canvasTextAutoLine(userArr[i],canvas1,10,90+70*i,12);

                    userObject[userArr[i]].height =72+70*i;
                    context.lineWidth = 1;
                    context.strokeStyle = "#dedede";
                    context.moveTo(85,userObject[userArr[i]].height);
                    context.lineTo(canvasWidth,userObject[userArr[i]].height);
                    context.closePath();
                    context.stroke();
                    context.beginPath();
                    context.fillStyle = "#dedede";
                    context.arc(85,userObject[userArr[i]].height,3,0,Math.PI*2,true); //Math.PI*2是JS计算方法，是圆
                    context.fill();
                    context.closePath();
                    context.stroke();
                }

                //第三步，绘制交易连线、金额、日期
                //3.1连线的起始位置
                for(var i=0;i<flowArr.length;i++){
                    context.beginPath();
                    context.moveTo(145+80*i,userObject[flowArr[i].from].height);
                    context.lineTo(145+80*i,userObject[flowArr[i].to].height);
                    //绘制文本
                    //设置字体样式
                    context.font = "12px";
                    //设置字体填充颜色
                    context.fillStyle = "#333";
                    //从坐标点(50,50)开始绘制文字
                    if(userObject[flowArr[i].from].height-userObject[flowArr[i].to].height<0){
                        context.fillText(flowArr[i].time,115+80*i, userObject[flowArr[i].from].height-5);
                        context.fillText(flowArr[i].date,115+80*i, userObject[flowArr[i].from].height-20);
                    }
                    if(userObject[flowArr[i].from].height-userObject[flowArr[i].to].height>0){
                        context.fillText(flowArr[i].date,115+80*i, userObject[flowArr[i].from].height+15);
                        context.fillText(flowArr[i].time,115+80*i, userObject[flowArr[i].from].height+30);
                    }
                    if(userObject[flowArr[i].from].height-userObject[flowArr[i].to].height<0){
                        context.fillText(flowArr[i].money,135+80*i, userObject[flowArr[i].to].height+12);
                    }
                    if(userObject[flowArr[i].from].height-userObject[flowArr[i].to].height>0){
                        context.fillText(flowArr[i].money,135+80*i, userObject[flowArr[i].to].height-5);
                    }

                    context.lineWidth = 1;
                    if(userObject[flowArr[i].from].height>userObject[flowArr[i].to].height){
                        context.strokeStyle = "#ff8547";
                    }else{
                        context.strokeStyle = "#178cf7";
                    }

                    //画箭头头部
                    var sp={x:145+80*i,y:userObject[flowArr[i].from].height};
                    var ep={x:145+80*i,y:userObject[flowArr[i].to].height};
                    var h=_calcH(sp,ep,context);
                    context.moveTo(ep.x,ep.y);
                    context.lineTo(h.h1.x,h.h1.y);
                    context.moveTo(ep.x,ep.y);
                    context.lineTo(h.h2.x,h.h2.y);
                    context.closePath();
                    context.stroke();
                }
                $(".loadingMask").hide();
            },
            error:function(){
            	$(".loadingMask").hide();
   		    }
        })
    }
    
    function loadD3(checkedAccount){
    	let param={
    			"checkedAccount":checkedAccount.join(','),
    			"casemanageId":parent.caseId,
    			"starTime":getMyDate(monthAnalysis.form.beginTime),
    			"endTime":getMyDate(monthAnalysis.form.endTime),
    			"minMoney":monthAnalysis.form.minMoney,
    			"maxMoney":monthAnalysis.form.maxMoney,
    			"days":monthAnalysis.form.days,
    			"levels":monthAnalysis.form.levels,
    			"sign":monthAnalysis.form.sign,
    			"detailKeyword":monthAnalysis.form.detailKeyword
    		};
    	 $.ajax({
   		    type : 'post',
   		    async :true,
   		    data: param,
   		    url : '${ctx}/bill/stream/moneyFlowPersonalD3',
   		    dataType: 'json',
   		    success:function (result) {
   	            if(result.nodes && result.nodes.length){
   	            	d3view.reload(result.nodes,result.links,"#hidebox");
   	            }else{
   	            }
            	$(".loadingMask").hide();
   		    },
   		    error:function(){
            	$(".loadingMask").hide();
   		    }
   		});
    }
    
    function _checkedCallback() {
        var checked = parent.parent._checkedAccount;
        if(checked&&checked.length>=1){
            var str ='';
            str = checked[0].split("_")[0];
            for (var i=0;i<checked.length;i++){
                if (checked[i].split("_")[0]==str){

                }else {
                    monthAnalysis.options=[];
                    monthAnalysis.form.detailKeyword="";
                    toastr.success("请选择一个主体");
                    return false;
                }
            }
           	monthAnalysis.options=[];
            monthAnalysis.form.detailKeyword="";
           	$.ajax({
        		 type : 'post',
        		 async :true,
        		 data: {casemanageId:parent.caseId,"checkedAccount":checked.join(',')},
        		 url : '${ctx}/bill/stream/getRivals',
        		 dataType: 'json',
        		 success:function (result) {
        		 	monthAnalysis.options=result;
        		 }
        	});
        }else{
            monthAnalysis.options=[];
            monthAnalysis.form.detailKeyword="";
            toastr.success("请选择一个主体");
        }
    }
    
    function _checkedCallback2(flag) {
        var checked = parent.parent._checkedAccount;
        if(checked&&checked.length>=1){
            var str ='';
            str = checked[0].split("_")[0];
            for (var i=0;i<checked.length;i++){
                if (checked[i].split("_")[0]==str){

                }else {
                    toastr.success("请选择一个主体");
                    return false;
                }
            }

            if(monthAnalysis.showType==0){
            	$(".loadingMask").show();
	            loadD3(parent.parent._checkedAccount);
            }else if(monthAnalysis.showType==1){
            	$(".loadingMask").show();
	            moneyFlow(parent.parent._checkedAccount);
            }else if(monthAnalysis.showType==2){
            	$(".loadingMask").show();
            	setTimeout(function(){
	            	loadZzjg(parent.parent._checkedAccount);
            	},100);
            }else if(monthAnalysis.showType==3){
            	firstTable(parent.parent._checkedAccount);
            }
        }else{
            toastr.success("请选择一个主体");
        }
    }

    function firstTable(checkedAccount){
		setTimeout(function(){
	    	let param={
	   			"checkedAccount":checkedAccount.join(','),
	   			"casemanageId":parent.caseId,
	   			"starTime":getMyDate(monthAnalysis.form.beginTime),
	   			"endTime":getMyDate(monthAnalysis.form.endTime),
	   			"minMoney":monthAnalysis.form.minMoney,
	   			"maxMoney":monthAnalysis.form.maxMoney,
	   			"days":monthAnalysis.form.days,
	   			"levels":monthAnalysis.form.levels,
	   			"sign":monthAnalysis.form.sign
	   		};
	        $('#dg').datagrid({
	            url:"${ctx}/bill/stream/moneyFlowPersonalData",//请求数据url
				method: 'post',
				queryParams : param,
				height:$("#dg-box").height(),
	            pagination: false,//允许分页
	            rownumbers: true,//行号
	            emptyMsg:"暂无信息",//加载数据为空时的信息
	            singleSelect: true,//只选择一行
	            checkOnSelect: false,
	            remoteSort:false,
	            autoRowHeight : false,//定义是否设置基于该行内容的行高度。设置为 false，则可以提高加载性能。
	            fitColumns: true,//真正的自动展开/收缩列的大小，以适应网格的宽度，防止水平滚动。
	            pageSize:30,
	            pageList:[30,50,100,150,200],
	            //表格的列
	            columns: [[
	                {
	                    field: 'accountBody',//域值
	                    title: '主体姓名'//内容
	                },
	                {
	                    field: 'accountBodyCard',//域值
	                    title: '主体卡号'//标题
	                },
	                {
	                    field: 'accountRival',//域值
	                    title: '对方姓名',
	                },
	                {
	                    field: 'accountRivalCard',//域值
	                    title: '对方卡号',//内容
	                },
	                {
	                    field: 'accountMoney',//域值
	                    title: '交易金额',
	                    sortable: true,//启用排序
	                    formatter:function (value,row,index) {
	                        if(!value) return 0;
	                        if (Number.isInteger(value)) {
	                            return value.toString().replace(/(\d)(?=(\d{3})+$)/g,'$1,');
	                        } else {
	                            return value.toString().replace(/(\d)(?=(\d{3})+\.)/g,'$1,');
	                        }
	                    },
	                    sorter:function(a,b){
	                    	var number1 = parseFloat(a);
	                    	var number2 = parseFloat(b);
	                    	return (number1 > number2 ? 1 : -1);
	        			}
	                },
	                {
	                    field: 'sign',//域值
	                    title: '资金流向',
	                    formatter:function (value,row,index) {
	                   	 	if(value && value==1){
	                            return '支出';
	                        }else if(value && value==0){
	                            return '收入';
	                        }else{
	                            return '-';
	                        }
	                   }
	                },
	                {
	                    field: 'tradeDate',//域值
	                    title: '交易日期',//内容
	                    sortable: true,//启用排序
	                    formatter:function (value,row,index) {
	                    	 if(value){
	                             var date = new Date(value);
	                             return formatDate(date, 'yyyy-MM-dd hh:mm:ss');
	                         }else{
	                             return '-';
	                         }
	                    },
	                    sorter:function(a,b){
	                    	var number1 = parseFloat(a);
	                    	var number2 = parseFloat(b);
	                    	return (number1 > number2 ? 1 : -1);
	        			}
	                }
	            ]],
	            onLoadSuccess: function (data) {
	                checkedAccount = null;
	            },
	            onHeaderContextMenu: function(e, field){
	                e.preventDefault();
	                if (!cmenu){
	                    createColumnMenu();
	                }
	                cmenu.menu('show', {
	                    left:e.pageX,
	                    top:e.pageY
	                });
	            }
	        });
		},100);
	}
    /*列显示下拉框*/
    var cmenu;
    function createColumnMenu(){
        cmenu = $('<div/>').appendTo('body');
        cmenu.menu({
            onClick: function(item){
                if (item.iconCls == 'icon-ok'){
                    $('#dg').datagrid('hideColumn', item.name);
                    cmenu.menu('setIcon', {
                        target: item.target,
                        iconCls: 'icon-empty'
                    });
                } else {
                    $('#dg').datagrid('showColumn', item.name);
                    cmenu.menu('setIcon', {
                        target: item.target,
                        iconCls: 'icon-ok'
                    });
                }
            }
        });
        var fields = $('#dg').datagrid('getColumnFields');
        for(var i=0; i<fields.length; i++){
            var field = fields[i];
            var col = $('#dg').datagrid('getColumnOption', field);
            cmenu.menu('appendItem', {
                text: col.title,
                name: field,
                iconCls: 'icon-ok'
            });
        }
    };

    // 下载Canvas元素的图片
    function downloadCanvasIamge(canvas, name) {
        // 通过选择器获取canvas元素
        var canvas = document.querySelector(canvas)
        canvas.style.backgroundColor='#fff';
        // 使用toDataURL方法将图像转换被base64编码的URL字符串
        var url = canvasToImage('#fff',canvas);
        // 生成一个a元素
        var a = document.createElement('a')
        // 创建一个单击事件
        var event = new MouseEvent('click')

        // 将a的download属性设置为我们想要下载的图片名称，若name不存在则使用‘下载图片名称’作为默认名称
        a.download = name || '下载图片名称'
        // 将生成的URL设置为a.href属性

        a.href = url

        // 触发a的单击事件
        a.dispatchEvent(event)
    }
    function canvasToImage(backgroundColor,canvas) {
        //cache height and width
        var w = canvas.width;
        var h = canvas.height;

        var data;
        var canvas1=document.getElementById("canvas1")
        var context = canvas1.getContext("2d");
        if(backgroundColor)
        {
            //get the current ImageData for the canvas.
            data = context.getImageData(0, 0, w, h);

            //store the current globalCompositeOperation
            var compositeOperation = context.globalCompositeOperation;

            //set to draw behind current content
            context.globalCompositeOperation = "destination-over";

            //set background color
            context.fillStyle = backgroundColor;

            //draw background / rect on entire canvas
            context.fillRect(0,0,w,h);
        }

        //get the image data from the canvas
        var imageData = canvas.toDataURL("image/jpg",0.1);

        if(backgroundColor)
        {
            //clear the canvas
            context.clearRect (0,0,w,h);

            //restore it with original / cached ImageData
            context.putImageData(data, 0,0);

            //reset the globalCompositeOperation to what it was
            context.globalCompositeOperation = compositeOperation;
        }

        //return the Base64 encoded data url string
        return imageData;
    }
var Text = require('zrender/shape/Text');
var ImageShape = require('zrender/shape/Image');
var Rectangle = require('zrender/shape/Rectangle');
var dom = document.getElementById('chart-panel');
dom.style.width = 1680 + 'px';
dom.style.height = 1000 + 'px';

var data1={"children":[]};
var data2={"children":[]};

function loadZzjg(checkedAccount){
	var data1={"children":[]};
	var data2={"children":[]};
	 $.ajax({
         url:'${ctx}bill/stream/moneyFlowPersonalZzjg',
         data:{
         	"checkedAccount":checkedAccount.join(','),
 			"casemanageId":parent.caseId,
 			"starTime":getMyDate(monthAnalysis.form.beginTime),
 			"endTime":getMyDate(monthAnalysis.form.endTime),
 			"minMoney":monthAnalysis.form.minMoney,
 			"maxMoney":monthAnalysis.form.maxMoney,
 			"days":monthAnalysis.form.days,
 			"levels":monthAnalysis.form.levels,
 			"sign":monthAnalysis.form.sign,
 			"detailKeyword":monthAnalysis.form.detailKeyword
		 },
         dataType:'json',
         type:'post',
         async:false,
         traditional: true,
         success:function (result) {
        	 if(result.data1){
        		 data1 = result.data1;
        		 itera(data1.children);
        	 }
        	 if(result.data2){
        		 data2 = result.data2;
        		 itera(data2.children);
        	 }
        	 option = {
      			    "title": {
      			        "text": ""
      			    },
      			    "series": [{
      			        "type": "tree",
      			        "orient": "vertical",
      			        "nodePadding": 25,
      			        "layerPadding": 40,
      			        "symbol": "circle",
      			        "roam": true,
      			        "rootLocation": {
      			            "x": "50%",
      			            "y": "50%"
      			        },
      			        "direction": "inverse",
      			        "data": data1.children
      			    }, {
      			        "type": "tree",
      			        "orient": "vertical",
      			        "nodePadding": 25,
      			        "layerPadding": 40,
      			        "symbol": "circle",
      			        "roam": true,
      			        "rootLocation": {
      			            "x": "50%",
      			            "y": "50%"
      			        },
      			        "data": data2.children
      			    }]
      			};
        	 myChart = echarts.init(document.getElementById('chart-panel'));
        	 myChart.setOption(option);
        	 initZrender();
        	 
        	 myChart.getZrender().on("mousedown", function (param){   
       			isDrag = true;
       			dragStartPos = [param.event.x,param.event.y];
       			
       		});
       		myChart.getZrender().on("mouseup", function (param){  
       			if(dragStartPos[0]==param.event.x&&dragStartPos[1]==param.event.y){
       				isDrag = false; 
       			}
       			dragStartPos = [];
       		});

       		myChart.getZrender().on('click', function(e){
       			if(isDrag) return;
       			if(e.target&&e.target.clickcom){
       				troggleTree(data1,data2,e.target.keyNo,e.target.treeId);
       			}
       		});
       		$(".loadingMask").hide();
         },
         error:function(){
       		$(".loadingMask").hide();
         }
	 });
}

function itera(objs){
	if(objs && objs.length>0){
		for(let i=0;i<objs.length;i++){
			let obj = objs[i];
			obj.clickable=false;
			obj.labelClick=false;
			obj.treeId=1;
			if(obj.symbol=='arrowdown'){
				obj.hoverable=false;
				obj.itemStyle={
	                    "normal": {"color": "#128bed","borderWidth": 0,"label": {"show": true,"position": "right","textStyle": {"fontFamily": "MicroSoft YaHei","fontSize": 12,"fontStyle": "normal"}}},
	                    "emphasis": {"color": "#128bed","borderWidth": 0,"label": {"show": true,"position": "right","textStyle": {"fontFamily": "MicroSoft YaHei","fontSize": 12,"fontStyle": "normal"}}}
	                };
				obj.lineStyle={"width": 1,"color": "#333"};
				obj.tooltip={"show": false};
				obj.symbolSize=[12, 12];
			}else{
				obj.KeyNo=Math.random()+"";
				obj.treeId=Math.random()+"";
				obj.editable=false;
				obj.Name = obj.name;
				if(obj.name.length>10){
					obj.name = obj.Name.substring(0,10)+"\n"+obj.Name.substring(10);
				}
				if(obj.level){
					obj.Level=obj.level;
					obj.symbolSize=[146,62];
				}else{
					obj.symbolSize=[272,52];
				}
				if(obj.down && (monthAnalysis.form.sign==1)){
					obj.isTouzi=true;
				}
				if(obj.children && obj.children.length>0){
					if(obj.level && obj.level<=3 && obj.level>0){
						obj.extend=2;
					}else if(obj.level && obj.level>3){
						obj.extend=1;
					}
					if(monthAnalysis.form.sign==0){
						obj.labelClick=true;
						obj.Org=0;
						obj.editable=true;
					}
				}
				obj.itemStyle={
                    "normal": {"color": "#fff","borderWidth": 1,borderColor: "#ccc","label": {"show": true,"position": "inside","textStyle": {"fontFamily": "MicroSoft YaHei","fontSize": 12,"fontStyle": "normal",color: "#333"}}},
                    "emphasis": {borderColor: "rgba(255,255,255,0)",borderWidth: "1",color: "rgba(255,255,255,0)"}
                };
			}
			itera(obj.children);
		}
	}
}

var isDrag;
var dragStartPos;

function troggleTree(data1,data2,KeyNo,tid){
    getNode(data1);
    getNode(data2);
    function getNode(data){
        if(!data) return;
        if(data.KeyNo&&data.KeyNo==KeyNo && data.treeId==tid){
            if(data.children){
                data._children = data.children;
                data.children = null;
                data.extend = 1;
                //data.symbol = 'circleCross';
            }else if(data._children){
                data.children = data._children;
                data._children = null;
                data.extend = 2;
				//获取内容
            }else{
				console.log("注意，这里就要动态加载节点下的数据了");
			}
            return;
        }
        if(data.children){
            for(var i=0;i<data.children.length;i++){
                getNode(data.children[i]);
            }
        }
    }
    myChart.clear();
    myChart.setOption(option);  
    initZrender();  
}

function initZrender(){
	var shapeList = myChart.getZrender().storage.getShapeList();
	for(var i=0;i<shapeList.length;i++){
        if(shapeList[i].clickcom||shapeList[i].ndelete){
            myChart.getZrender().delShape(shapeList[i].id);
        }
        if(shapeList[i]._echartsData&&shapeList[i]._echartsData._data&&shapeList[i].style.text){
            shapeList[i].style.text = shapeList[i].style.text.replace(/^\s+|\s+$/g,'');
        }
    }
	for(var i=0;i<shapeList.length;i++){
		if(shapeList[i]._echartsData&&shapeList[i]._echartsData._data.extend){
			var iconImg = '';
			var isIE11 = (!!window.ActiveXObject || "ActiveXObject" in window);
			if(shapeList[i]._echartsData._data.extend==1){
				if(isIE11){
					iconImg = '${ctx}imgs/tupu_cross.png';
				}else{
					iconImg = '${ctx}imgs/tupu_cross.svg';
				}
			}else if(shapeList[i]._echartsData._data.extend==2){
				if(isIE11){
					iconImg = '${ctx}imgs/tupu_minus.png';
				}else{
					iconImg = '${ctx}imgs/tupu_minus.svg';
				}
				
			}
			var shapeY = shapeList[i].rotation[2];
			if(shapeList[i]._echartsData._data.isTouzi){
				shapeY = shapeY + shapeList[i].style.height/2;
			}else{
				 shapeY = shapeY - shapeList[i].style.height/2-18;
			}
			var shape = new ImageShape({
			style: {
				image:iconImg,
				x: shapeList[i].rotation[1]-9,
				y: shapeY,
				width:18,
				height:18
				
			}  
			});
			shape.keyNo = shapeList[i]._echartsData._data.KeyNo;
			shape.treeId = shapeList[i]._echartsData._data.treeId;
			shape.zlevel = 1;
			shape.z = 4;
			shape.ndelete = true;
			shape.clickcom = true;
			shape.hoverable = true;
			shape.clickable = true;
			myChart.getZrender().addShape(shape);
		}
	}
}

 function jietu(){
	var jietuMask=document.createElement("div");
	$(jietuMask).attr('style','position: fixed; background: #fff; z-index: 1000; top: 0px; bottom: 0px; left: 0px; right: 0px;');
	document.body.appendChild(jietuMask);

	var width = 1440;
	var height = 900;

	var minX = 0;
	var maxX = 0;
	var minY = 300;
	var maxY = 0;
	var moveDown = 0;
	var moveRight = 0;

	var shapeList = myChart.getZrender().storage.getShapeList();
	for(var i=0;i<shapeList.length;i++){
		if(shapeList[i].style&&shapeList[i].style.iconType=='rectangle'){
			if(shapeList[i].style.x>maxX){
				maxX = shapeList[i].style.x;
			}
			if(shapeList[i].style.x<minX){
				minX = shapeList[i].style.x;
			}
			if(shapeList[i].style.y>maxY){
				maxY = shapeList[i].style.y;
			}
			if(shapeList[i].style.y<minY){
				minY = shapeList[i].style.y;
			}
		}
	}

	if((maxX-minX+300)>width){
		width = maxX-minX+300;
		moveRight = -(maxX+minX-myChart.getZrender().getWidth()+146)/2;
		
	}
	if((maxY-minY+300)>900){
		height = maxY-minY+300;
	}

	moveDown = -(maxY+minY-myChart.getZrender().getHeight())/2-85;
	
	var layer = myChart.getZrender().painter._layers[1];
	var bS = layer.scale.concat();
	var bP = layer.position.concat();

	layer.scale = [1,1,0,0];
	layer.position = [0,0];

	var bW = myChart.getZrender().getWidth();
	var bH = myChart.getZrender().getHeight();

	$('#chart-panel').width(width);
	$('#chart-panel').height(height);
	
	var zdW = myChart.getZrender().getWidth();
	var zdH = myChart.getZrender().getHeight();
	
	
	


	myChart.resize();

	myChart.getZrender().painter.refresh();

	initZrender(true);

	layer.position[0] = moveRight;
	layer.position[1] = moveDown;

	var shape1 = new Rectangle({
		style: {
			x: -1000-moveRight,
			y: -1000-moveDown,
			width: width+1000,
			height: height+1000,
			color:'#fff'
		} 
	});
	shape1.zlevel=1;
	shape1.z=-2;
	shape1.ndelete = true;
	myChart.getZrender().addShape(shape1);


	for(var i=0;i<width+100;i+=300){
		for(var j=0;j<height+100;j+=228){
			var shapeSy = new ImageShape({
				style: {
					image:'${ctx}imgs/shuiyin.png',
					x: i-moveRight,
					y: j-moveDown,
					width:300,
					height:228
					
				}  
			});
			shapeSy.zlevel=1;
			shapeSy.z=-1;
			shapeSy.ndelete = true;
			myChart.getZrender().addShape(shapeSy);
		}
	}

	var shape3 = new Text({
		style: {
			x: width/2-165-moveRight,
			y: height-30-moveDown,
			text: '层级关系图',
			strokeColor:'#999',
			color : '#999' ,
			textFont:'normal 12px 微软雅黑',
			lineWidth :0,
		}  
	});
	shape3.zlevel=1;
	shape3.z=-1;
	shape3.ndelete = true;
	myChart.getZrender().addShape(shape3);

	setTimeout(function() {
		var canvas = $('#chart-panel canvas')[1];
		download2(canvas,'jpg');
		
		$('#chart-panel').width('100%');
		$('#chart-panel').height(bH);
		myChart.resize();
		layer.scale = bS;
		layer.position = bP;
		myChart.getZrender().render();
		initZrender();
		$(jietuMask).css('display','none');
	}, 300);
}

function download2(canvas,type) {
    if(!!window.ActiveXObject || "ActiveXObject" in window){
        var blob = canvas.msToBlob();
        window.navigator.msSaveBlob(blob, new Date().toLocaleDateString() + '.png');
        return;
    }
    type = 'png';
    //设置保存图片的类型
    var imgdata = canvas.toDataURL(type);
    //将mime-type改为image/octet-stream,强制让浏览器下载
    var fixtype = function (type) {
        type = type.toLocaleLowerCase().replace(/jpg/i, 'jpeg');
        var r = type.match(/png|jpeg|bmp|gif/)[0];
        return 'image/' + r;
    }
    imgdata = imgdata.replace(fixtype(type), 'image/octet-stream')
    //将图片保存到本地
    var saveFile = function (data, filename) {
        var link = document.createElement('a');
        link.href = data;
        link.download = filename;
        var event = document.createEvent('MouseEvents');
        event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
        link.dispatchEvent(event);
    }
    var filename = new Date().toLocaleDateString() + '.' + type;
    saveFile(imgdata, filename);
}
		</script>
<style>
    .el-tabs__item.is-active {
        color: #287CDF;
    }
    .el-tabs__active-bar{
        background-color: #287CDF;
        height: 2px;
    }
    .el-tabs__header{
        margin: 0px 0 7px!important;
        width: 100%;
        z-index: 2;
        background: #fff;
        position: fixed;
    }
    .svzjRight {
        margin-top: -30px;
    }
    .svzjRight::-webkit-scrollbar {/*滚动条整体样式*/
        height: 6px;
    }
    .loadimgbtn{
        background: url(${ctx}/imgs/login-imgs/loadimg.png);
        display: inline-block;
        width: 14px;
        height: 16px;
        position: absolute;
        right: 35px;
        cursor: pointer;
    }
    .loadimgbtn:hover{
        background: url(${ctx}/imgs/login-imgs/loadimgh.png);
        display: inline-block;
        width: 14px;
        height: 16px;
        position: absolute;
        right: 35px;
    }
    .svzjRight{
        overflow-y: auto;
    }
    .refshj .el-form-item__label {
        margin-left: -16px;
        margin-right: -8px;
    }
    .svzjFontCon {
        text-align: center;
    }
    span.zcline {
        display: inline-block;
        width: 20px;
        height: 2px;
        background-color: #3b9ef3;
        border-radius: 1px;
        vertical-align: super;
        margin-right: 5px;
    }
    span.hlline{
        display: inline-block;
        width: 20px;
        height: 2px;
        background-color: #e6965c;
        border-radius: 1px;
        vertical-align: super;
        margin-right: 5px;
    }
    span.zcfont {
        margin-right: 10px;
    }
    .svzjLeft{
        float: left;
    }
    .svzjRen {
        text-align: center;
        padding-top: 34px;
    }
    .svzjimg {
        width: 12px;
        height: 15px;
        background: url("../../../imgs/svzjimg.png") no-repeat;
        margin-left: 47px;
    }
    .svzjCircle {
        width: 8px;
        height: 8px;
        background-color: #eef1f9;
        margin-top: 69px;
        border-radius: 50%;
    }
    .el-table__header,
    .el-table__body{
        width: 100%!important;
    }
    .account_treeview_buttonarea{
        margin-top: 40px;
    }
    .el-form-item.form_z {
        margin-right: 11px !important;
    }
    .zcdcon {
        display: inline-block;
    }
    .robot-table {
        padding: 0 10px;
    }
    .el-pagination {
        padding-top: 10px;
        padding-bottom: 10px;
    }
    .stream_search {
        background: #fff;
        width: 100%;
        padding-top: 10px;
        margin-bottom:5px;
    }
    .el-form-item__label{
        color: #6f7689;
        font-weight: 400;
        font-size: 13px;
    }
    .el-form--inline .el-form-item{
        margin-right: 18px;
    }
    .casemanage-switch .casemanage-zhexiantu.active {
        background-color: #4595ec;
    }
    .casemanage-switch .casemanage-zhexiantu {
        float: left;
        width: 50px;
        height: 35px;
        display: block;
        cursor: pointer;
        border-top-left-radius: 5px;
        border-bottom-left-radius: 5px;
        line-height: 35px;
        text-align: center;
    }
    #font_zhexian{
        color: #C1C2C3;
        font-size: 18px;
    }
    #font_zhexian.active{
        color: #F4F9FE;
    }
    .el-input__inner{
        border-color: #D2D6DE;
        height: 34px;
        width: 179px;
        font-size: 12px;
        border-color: #e4e4e4;
    }
    .el-input__inner:hover{
        border-color:#4695ed;
    }
    .el-input__inner:focus{
        border-color:#4695ed;
    }
    .el-dialog--small{
        width: 88%;
    }
    .el-button--primary{
        background-color:#4695ed;
        border-color:#4695ed;
        width: 70px;
    }
    .el-button--primary:focus, .el-button--primary:hover{
        background: #61a8f5;
        border-color: #61a8f5;
    }
    button.el-button.el-button--default.reset_button {
        background-color: #f4f4f4;
        color: #444;
        border-color: #ddd;
    }
    .button.el-button.el-button--default.reset_button:focus, button.el-button.el-button--default.reset_button:hover{
        border-color: #adadad;
        background-color: #e7e7e7;
    }
    .el-button{
        width: 70px;
    }
    .el-breadcrumb{
        margin-top: 15px;
        margin-bottom: 15px;
        font-size: 17px;
    }
    #days input,#minmoney input,#maxmoney input,#levels input{
    	width:60px!important;
    }
	select.zjzysign {
		height: 30px;
		width: 55px;
		border-color: #e4e4e4;
		font-size: 12PX;
		margin-right:18px;
		margin-top:3px;
	}
	.fl{float:left;}
	.d3-toolbox{display:block;position:fixed;left:19px;top:95px;width:220px;min-height:100px;border:1px solid #ddd;background:#fff;}
	.d3-viewbox{margin:11px;float:left;}
	.d3-viewbox3{margin:11px 11px 0 11px;float:left;}
	.d3-viewbox2{padding:5px;margin:5px;float:left;border:1px solid #ddd;}
	.d3-view-type{float:left;width:60px;height:24px;line-height:24px;border:1px solid #ddd;color:#000;font-family:微软雅黑;margin-left:5px;border-radius:3px;display: block;text-align:center;cursor:pointer;}
	.d3-view-type:hover{border:none;color:#fff;background:#52a1fe;}
	.d3-view-type.current{border:none;color:#fff;background:#52a1fe;cursor:auto;}
	.d3-purple{float:left;width:90px;height:16px;color:#fff;background:#7200da;}
	.d3-yellow{float:left;width:90px;height:16px;color:#fff;background:#f9c00c;}
	.d3-blue{float:left;width:90px;height:16px;color:#fff;background:#007efe;}
	.d3-money{float:left;margin:5px 0;}
	.d3-money input{width:100px;border:1px solid #ddd;}
	.d3-button{width:85px;height:30px;line-height:30px;color:#fff;background:#52a1fe;font-family:微软雅黑;border-radius:3px;display: block;text-align:center;cursor:pointer;}
	.link {fill: none;stroke: #ccc;stroke-width: 1.5px;}
	.dc {margin-left:5px;}
	#hidebox {
		top: 23px;
		left: 2%;
		border-radius: 5px;
		background-color:#fff;
		z-Index:9999;
		padding: 10px;
		overflow:hidden;
	}
	.set-d3box{
		width: 30px;
		height: 30px;
		background-color: #87CEFA;
		border-radius: 50%;
		line-height: 30px;
		text-align: center;
		color: white;
		position: absolute;
		top: 80px;
		z-index: 9;
		cursor:pointer;
	}
	.set-d3box:active {
		background-color: #00BFFF;
	}
	.casemanage-switchtip div i.gxt {margin-left: 10px;margin-top: 5px;background: url(${ctx}imgs/cut-imgs/gxt.png) 0% 0% / 15px 15px no-repeat;}
	.casemanage-switchtip div i.sjz {margin-left: 10px;margin-top: 5px;background: url(${ctx}imgs/cut-imgs/sjz.png) 0% 0% / 15px 15px no-repeat;}
	.casemanage-switchtip div i.zzjg {margin-left: 10px;margin-top: 5px;background: url(${ctx}imgs/cut-imgs/zzjg.png) 0% 0% / 15px 15px no-repeat;}
	.casemanage-switchtip div i.dc {margin-left: 10px;margin-top: 5px;background: url(${ctx}imgs/cut-imgs/dc.png) 0% 0% / 15px 15px no-repeat;}
	.casemanage-switchtip div i.ldx {margin-left: 10px;margin-top: 5px;background: url(${ctx}imgs/cut-imgs/ldx.png) 0% 0% / 15px 15px no-repeat;}
	.casemanage-switchtip div.active i.gxt {margin-left: 10px;margin-top: 5px;background: url(${ctx}imgs/cut-imgs/gxth.png) 0% 0% / 15px 15px no-repeat;}
	.casemanage-switchtip div.active i.sjz {margin-left: 10px;margin-top: 5px;background: url(${ctx}imgs/cut-imgs/sjzh.png) 0% 0% / 15px 15px no-repeat;}
	.casemanage-switchtip div.active i.zzjg {margin-left: 10px;margin-top: 5px;background: url(${ctx}imgs/cut-imgs/zzjgh.png) 0% 0% / 15px 15px no-repeat;}
	.casemanage-switchtip div.active i.ldx {margin-left: 10px;margin-top: 5px;background: url(${ctx}imgs/cut-imgs/ldxh.png) 0% 0% / 15px 15px no-repeat;}
	.dropdown-menu .nav-header{padding:15px;background:none}
	.casemanage-switchtip{top:0px;position:relative;float:right;margin-bottom:0;}
	.casemanage-switchtip div{width:34px;}
	.casemanage-switchtip div i{margin-left: 10px!important;}
	.loadingMask{width: 100%;height:100%;position: absolute;top:0px;left:0px; background:rgba(0,0,0,0);z-index:999;}
	.loading{display: flex;flex-flow: row nowrap;align-items: center;justify-content: space-between;width: 2em; position: absolute;top:50%;left:50%;margin-left: -1em;margin-top:-1em;}
	.loading span {width: 0.3em;height: 1em;background-color: #23b7e5;}
	.loading span:nth-of-type(1) {animation: grow 1s -0.45s ease-in-out infinite;}
	.loading span:nth-of-type(2) {animation: grow 1s -0.3s ease-in-out infinite;}
	.loading span:nth-of-type(3) {animation: grow 1s -0.15s ease-in-out infinite;}
	.loading span:nth-of-type(4) {animation: grow 1s ease-in-out infinite;}
	@keyframes grow {
	  0%,
	  100% {
	    transform: scaleY(1);
	  }
	  50% {
	    transform: scaleY(2);
	  }
	}
</style>
